package xyz.zhouxf.rpc.transport.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxf.rpc.entity.RpcRequest;
import xyz.zhouxf.rpc.entity.RpcResponse;
import xyz.zhouxf.rpc.factory.SingletonFactory;
import xyz.zhouxf.rpc.handler.RpcHandler;

/**
 * @author zhouxf
 * @date 2022/9/2
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private final RpcHandler rpcHandler;

    NettyServerHandler() {
        this.rpcHandler = SingletonFactory.getInstance(RpcHandler.class);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest) throws Exception {
        try {
            log.info("服务器收到请求：{}",rpcRequest);
            Object result = rpcHandler.handle(rpcRequest);
            if(channelHandlerContext.channel().isActive() && channelHandlerContext.channel().isWritable()) {
                channelHandlerContext.writeAndFlush(RpcResponse.success(result, rpcRequest.getRequestId()));
            }else {
                log.error("通道不可写");
            }
        }finally {
            ReferenceCountUtil.release(rpcRequest);
        }
    }
}
